package clientprometheus

import (
	"context"
	prom "github.com/prometheus/client_golang/prometheus"
	"google.golang.org/grpc"
	"google.golang.org/grpc/status"
	"start/pkg/prometheus"
	"strconv"
	"time"
)

func PrometheusInterceptor(serverNamespace string) grpc.UnaryClientInterceptor {
	// 直方图配置
	var histogramVec *prom.HistogramVec

	// 创建计数器类型的指标
	var counterVec *prom.CounterVec

	serverNamespace = serverNamespace + "_grpc_client"

	histogramVec = prometheus.NewHistogramVec(prom.HistogramOpts{
		Namespace: serverNamespace,
		Subsystem: "requests",
		Name:      "grpc_duration_ms",
		Help:      "grpc client requests duration(ms).",
		Buckets:   []float64{5, 10, 25, 50, 100, 250, 500, 1000},
	}, []string{"method"})

	counterVec = prometheus.NewCounterVec(prom.CounterOpts{
		Namespace: serverNamespace,
		Subsystem: "requests",
		Name:      "grpc_code_total",
		Help:      "grpc client requests code count.",
	}, []string{"method", "code"})

	return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn,
		invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {

		startTime := time.Now()
		err := invoker(ctx, method, req, reply, cc, opts...)
		//记录了耗时
		histogramVec.WithLabelValues(method).Observe(float64(time.Since(startTime) / time.Millisecond))

		//记录了状态码
		counterVec.WithLabelValues(method, strconv.Itoa(int(status.Code(err)))).Inc()
		return err
	}
}
